package mp

import (
	"context"
	"strings"

	"ruikc.com/server/api/internal/db"
	"ruikc.com/server/api/internal/svc"
	"ruikc.com/server/api/internal/types"
	"ruikc.com/server/models"
	"ruikc.com/server/utils"
	xb "xorm.io/builder"

	"github.com/jinzhu/copier"
	"github.com/zeromicro/go-zero/core/logx"
)

type CourseListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewCourseListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CourseListLogic {
	return &CourseListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *CourseListLogic) CourseList(req *types.CourseSearch) (resp *types.CourseList, err error) {
	var datas []models.Course
	conds := xb.And(xb.Gt{"id": 0})
	if req.Keyword != "" {
		conds = conds.And(xb.Like{"title", "'%" + req.Keyword + "%'"})
	}
	if req.Cid1 != 0 {
		conds = conds.And(xb.Eq{"cid1": req.Cid1})
	}
	if req.Cid2 != 0 {
		conds = conds.And(xb.Eq{"cid2": req.Cid2})
	}
	//得到总条数
	total := db.CountData(&models.Course{}, conds)
	//得到所有分类
	cids := db.ClassifyMap()
	//得到所有的讲师
	instructors := db.InstructorMap()
	db.FindPageDatas(&datas, conds, req.Page)

	items := []types.Course{}
	for _, v := range datas {
		tmp := types.Course{}
		copier.Copy(&tmp, &v)
		tmp.Cid1Title = cids[v.Cid1]
		tmp.Cid2Title = cids[v.Cid2]
		//遍历得到所有讲师信息
		for _, iv := range strings.Split(v.InstructorIds, ",") {
			itid := utils.StringToInt(iv)
			if itVa, ok := instructors[itid]; ok {
				itmp := types.Instructor{}
				copier.Copy(&itmp, itVa)
				tmp.Instructors = append(tmp.Instructors, itmp)
				tmp.InstructorIds = append(tmp.InstructorIds, iv)
			}
		}
		items = append(items, tmp)
	}
	return &types.CourseList{
		Total: int(total),
		Items: items,
	}, nil
}
